<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class ZPituitaryUserVisitLevel extends Model
{

    protected $table = 'z_pituitary_visit_level';

    protected $guarded = ['id'];

    // 计算入组时间到当前的月份数，对应相对的访视等级
    const VISIT_LEVEL = [
        1 => [0],
        3 => [1, 2, 3],
        4 => [4, 5, 6],
        5 => [7, 8, 9],
        6 => [10, 11, 12],
        7 => [13, 14, 15],
        8 => [16, 17, 18],
        9 => [19, 20, 21],
        10 => [22, 23, 24],
        11 => [25, 26, 27],
        12 => [28, 29, 30],
        13 => [31, 32, 33],
        14 => [34, 35, 36],
        15 => [37, 38, 39],
        16 => [40, 41, 42],
        17 => [43, 44, 45],
        18 => [46, 47, 48],
        19 => [49, 50, 51],
        20 => [52, 53, 54],
        21 => [55, 56, 57],
        22 => [58, 59, 60],
        23 => [61, 62, 63],
    ];
    // 一对多 就诊记录
    public function records()
    {
        return $this->hasMany('App\Models\ZPituitaryVisitRecords', 'visit_id');
    }

    /**
     *  获取最大访视信息
     * @param $userId
     * @return array
     */
    public static function getMaxVisitByUserId($userId)
    {
        $ret  = self::query()->selectRaw('max(visit_level) as visit_level,')
            ->where('user_id', $userId)
            ->first();

        return $ret ? $ret->toArray() : [];
    }

    /**
     * 获取用户的最大访视
     * @param $userId
     * @return mixed
     */
    public static function getMaxVisitInfo($userId)
    {
        $sql = "select id,visit_level from z_pituitary_visit_level where user_id = ? order by visit_level desc limit 1";
        $info = DB::selectOne($sql, [$userId]);

        $id = $info->id ?? 0;
        $level = $info->visit_level ?? 0;
        $time = '0001-01-01';

        if (!empty($id) && !empty($level)) {
            $sql = "select visit_at from z_pituitary_visit_records where visit_id = ? and  user_id = ? order by visit_at desc limit 1";

            $at = DB::selectOne($sql, [$id, $userId]);

            $time = $at->visit_at ?? '0001-01-01';
        }

        return ['visit_level' => $level, 'visit_at' => $time];
    }


    /**
     *  获取访视记录
     * @param $patientId
     * @return mixed
     */
    public static function getVisitHistory($patientId)
    {
        return self::query()->where('user_id', $patientId)
            ->get()
            ->toArray();
    }


    /**
     * 按照入组时间，推算当前属于哪个V
     * @param $joinTime string 入组时间
     * @param $visitAt  string 当前时间
     */
    public static function getVisitLevel($userId, $visitAt)
    {
        $join = ZPituitaryUser::query()->where('user_id', $userId)->first();
        if (empty($join)) {
            return false;
        }
        $join = $join->toArray();
        $firstTime = $join['created_at'];
        $months = Carbon::createFromFormat('Y-m-d', $visitAt)->diffInMonths($firstTime);

        //检查数据会有超前基准线的情况，超出V1 范围的就不归
        if ($firstTime > $visitAt) {
            if ($months > 1) {
                //数据超前基准线'
                return false;
            }else{
                $visitLevel = 1;
            }
        }else{
            $v = array_filter(self::VISIT_LEVEL, function ($v) use ($months) {
                return in_array($months, $v);
            });
            if (empty($v)) {
                //超过访视周期
                return 23;
            } else {
                $visitLevel = array_keys($v)[0];
            }
        }
        return $visitLevel;
    }

    
}
